package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.LogUtil;
import com.tjvib.util.PressUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.widget.AndroidScheduler;
import com.tjvib.widget.ItemGroup;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class AboutActivity extends BaseActivity {

    /**
     * 如果有apk下载链接，那么就可以把【//】注释内容解开，直接安装最新版apk
     * 注意，Manifest中需要新增权限<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
     */
//    private static final int REQUEST_INSTALL_PERMISSION = 5;

    private ImageView about_iv_logo;
    private TextView about_tv_ver;
    private ItemGroup about_ig_update, about_ig_feedback, about_ig_agreement;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_about;
    }

    @Override
    protected boolean initView() {
        about_iv_logo = findViewById(R.id.about_iv_logo);
        about_tv_ver = findViewById(R.id.about_tv_ver);

        about_ig_update = findViewById(R.id.about_ig_update);
        about_ig_update.setOnClickListener(v -> {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                if (!getPackageManager().canRequestPackageInstalls()) {
//                    // 弹出系统对话框，询问用户是否允许安装应用权限
//                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//                    intent.setData(Uri.parse("package:" + getPackageName()));
//                    startActivityForResult(intent, REQUEST_INSTALL_PERMISSION);
//                } else {
//                    // 已经有安装应用权限，可以直接安装应用
//                    installApk();
//                }
//            } else {
            // 安装应用权限不需要申请，可以直接安装应用
            installApk();
//            }
        });

        about_ig_feedback = findViewById(R.id.about_ig_feedback);
        about_ig_feedback.setOnClickListener(v -> {
            startActivity(new Intent(AboutActivity.this, FeedbackActivity.class));
        });

        about_ig_agreement = findViewById(R.id.about_ig_agreement);
        about_ig_agreement.setOnClickListener(v -> {
            Intent intent = new Intent(AboutActivity.this, WebActivity.class);
            intent.putExtra("URL", "http://122.152.206.37:8033/user-services-agreement.html");
            intent.putExtra("TITLE", "用户服务协议和隐私政策");
            startActivity(intent);
        });

        PressUtil.setPressChange(AboutActivity.this, about_ig_feedback, about_ig_update, about_ig_agreement);

        return true;
    }

    @Override
    protected boolean initData() {
        Glide.with(this)
                .load(R.mipmap.tjvib512)
                .into(about_iv_logo);
        about_tv_ver.setText(getVersionName(AboutActivity.this));

        return true;
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }


    private void installApk() {
        RetrofitHelper.getInstance().create()
                .getVersion()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        if (value.getCode() == SUCCESS) {
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(value.getData()));
                                getVersionCode(AboutActivity.this);
                                if (getVersionCode(AboutActivity.this) < jsonObject.getInt("id"))
                                    showHintDialog("存在新版本" + jsonObject.getString("versionName") + "，请前往应用商店更新");
//                                AppUpdateManager.Builder builder = new AppUpdateManager.Builder(AboutActivity.this);
//                                builder.apkUrl(jsonObject.getString("apkUrl"))
//                                        .updateContent(new String[]{"更新内容：", jsonObject.getString("modifyContent")})
//                                        .newVerName(jsonObject.getString("versionName"))
//                                        .updateForce(false)
//                                        .confirmBgColor(getColor(R.color.main_purple_0))
//                                        .cancelBgColor(getColor(R.color.main_grey_1))
//                                        .progressDrawable(R.color.main_purple_0)
//                                        .build();
                                else
                                    showHintDialog("当前已经是最新版本");
                            } catch (JSONException e) {
                                LogUtil.e("err e=" + e.getMessage());
                                throw new RuntimeException(e);
                            }
                        } else {
                            showErrorDialog("获取服务器版本信息失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showErrorDialog("异常：" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_INSTALL_PERMISSION) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                if (getPackageManager().canRequestPackageInstalls()) {
//                    installApk();
//                } else {
//                    ToastUtil.show("未允许安装应用权限");
//                }
//            }
//        }
    }


    public int getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        int versionCode = 10000;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
            LogUtil.e("packageInfo=" + packageInfo + "\nversionCode=" + versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    public String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
            LogUtil.e("packageInfo=" + packageInfo + "\nversionName=" + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            ToastUtil.show("获取版本号失败！");
            e.printStackTrace();
        }
        return versionName;
    }
}